import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';



class WebViewWithReturn extends StatefulWidget {
  @override
  State<WebViewWithReturn> createState() => _WebViewWithReturnState();
}

Future<bool> _requestCameraPermission() async {
  final status = await Permission.camera.request();
  if (status == PermissionStatus.granted) {
    return true;
  } else {
    // 权限被拒绝，提示用户
    return false;
  }
}

class _WebViewWithReturnState extends State<WebViewWithReturn> {

  final String initialUrl = Get.parameters['url']??'';
  final String back = Get.parameters['back']??'';


  //final String initialUrl;

  late String targetRoute = '';



  @override
  void initState() {
    super.initState();
    _requestCameraPermission();
  }

 

  @override
  Widget build(BuildContext context) {
    final totalHeight = MediaQuery.of(context).padding.top;
    return Scaffold(
        body: Container(
      margin: EdgeInsets.only(top: totalHeight),
      child: InAppWebView(
                      initialUrlRequest: URLRequest(url: WebUri(initialUrl)),
                      onWebViewCreated: (controller) async {
                        // _webViewController = controller;
                        // _configureJsCallFunction();
                        // if (testHtml) {
                        //   await controller.loadData(
                        //     data: testMobileHtml,
                        //   );
                        // }

                        controller.addJavaScriptHandler(
                          handlerName: 'onBackPressed',
                          callback: (args) async {
                           // final canGoBack = await controller.canGoBack();
                           print('888889');

                              Navigator.pop(context);

                            // if (canGoBack) {
                            //   controller.goBack();
                            // } else {
                            //   Navigator.pop(context);
                            // }

                          },
                        );

                        // controller.evaluateJavascript(source: """
                        //   window.addEventListener('popstate', function(event) {
                        //     window.flutter_inappwebview.callHandler('onBackPressed');
                        //   });
                        // """);
                      },
                      onConsoleMessage: (controller, consoleMessage) {
                        debugPrint("页面日志: ${consoleMessage.message}");
                      },
                      onLoadStart: (controller, url) {
                        setState(() {
                          // _isLoading = true;
                        });
                      },
                      onLoadStop: (controller, url) async {
                        if (kIsWeb) {
                            await controller.evaluateJavascript(
                              source: "window.flutter_inappwebview = { callHandler: function(handlerName) { window‌:ml-search[handlerName]; } };"
                            );
                        }

                        final canGoBack = await controller.canGoBack();



                          Uri uri = Uri.parse('$url');
                          Map<String, String> queryParameters = uri.queryParameters;

                          print(22222);
                          print('$url');
                          print(queryParameters);

                          String? iad = queryParameters['order_id']??queryParameters['id'];
                          String? code = queryParameters['code']??'';

                          print('$iad');
                         
                       
                         if(canGoBack){
                          if(code.isEmpty){
                                if (queryParameters['web'] == 'wode') {
                              Navigator.pop(context);

                            } else if(back == 'weitou'||back == 'jingjia'){
                                Get.offNamed('/web_tabs/market/entrust_success?id=$iad&back=$back');
                            }else if(back == 'suu'){
                                Get.offNamed('/web_tabs/details/pay_success?id=$iad');
                            }
                          }
                          
                         }
                         
                        setState(() {});
                      },
                      onProgressChanged: (controller, progress) {},
                      onReceivedError: (controller, request, error) {
                        debugPrint('加载失败: ${error.description}');
                      },
                      initialSettings: InAppWebViewSettings(
                        supportZoom: false,
                        javaScriptEnabled: true,
                        disableHorizontalScroll: false,
                        disableVerticalScroll: false,
                        horizontalScrollBarEnabled: false,
                        verticalScrollBarEnabled: false,
                        mediaPlaybackRequiresUserGesture: false,
                        allowsInlineMediaPlayback: true,
                        javaScriptCanOpenWindowsAutomatically: true,
                        transparentBackground: false,
                      ),
                      onReceivedServerTrustAuthRequest:
                                (controller, challenge) async {
                              // 允许不安全的 HTTPS 链接
                              return ServerTrustAuthResponse(
                                  action: ServerTrustAuthResponseAction.PROCEED);
                            },
                      // onDownloadStarting:
                      //     (controller, downloadStartRequest) async {
                      //   final url = downloadStartRequest.url.toString();
                      //   _downloadAndInstallApk(url);
                      //   return;
                      // },
                      onPermissionRequest: (controller, request) async {

                    
                        


                        final resources = <PermissionResourceType>[];
                        if (request.resources
                            .contains(PermissionResourceType.CAMERA)) {
                          final cameraStatus =
                              await Permission.camera.request();
                          if (!cameraStatus.isDenied) {
                            resources.add(PermissionResourceType.CAMERA);
                          }
                        }
                        if (request.resources
                            .contains(PermissionResourceType.MICROPHONE)) {
                          final microphoneStatus =
                              await Permission.microphone.request();
                          if (!microphoneStatus.isDenied) {
                            resources.add(PermissionResourceType.MICROPHONE);
                          }
                        }
                        // only for iOS and macOS
                        if (request.resources.contains(
                            PermissionResourceType.FILE_READ_WRITE)) {
                          final cameraStatus =
                              await Permission.camera.request();
                          final microphoneStatus =
                              await Permission.microphone.request();
                          if (!cameraStatus.isDenied &&
                              !microphoneStatus.isDenied) {
                            resources.add(
                                PermissionResourceType.CAMERA_AND_MICROPHONE);
                          }
                        }
                       

                        return PermissionResponse(
                            resources: resources,
                            action: resources.isEmpty
                                ? PermissionResponseAction.DENY
                                : PermissionResponseAction.GRANT);
                      },
                    ),
    ));
  }
}



 